<?php
/**
 * Created by PhpStorm.
 * User: bzyy
 * Date: 2015-7-23 13:56:54
 */

class PostruleregionModel extends BaseModel{

    public $table = 'post_rule_region';

    public $prikey = 'id';

    public $_autov = array(

        'rule_id' => array(
            'required'  => true,
            'filter'    => 'trim',
            'reg'   => '/\d+/'
        ),
        'express_id' => array(
            'required'  => true,
            'filter'    => 'trim',
            'reg'   => '/\d+/'
        ),

    );

    /**
     * 编辑一批元素
     * @auth bzyy
     * 2015-7-23 18:26:41
     */
    public function editregions($regions,$rules_id,$addon)
    {

        $cond = array();
        $cond['conditions'] = "rule_id='{$rules_id}'";
        $data = (array)$this->find($cond);

        $oldinfo = array();
        foreach($data as $val)
        {
            $oldinfo[$val['id']] = array($val['country'],$val['province'],$val['city'],$val['region']);
        }

        $ids_has = array();
        $regions_info = $this->region_address($regions);

        foreach($regions as $val)
        {
            $key_id = array_search($val,$oldinfo);
            $region = array();
            $region['express_id'] = $addon['express_id'];
            $region['rule_id'] = $rules_id;
            list($country,$province,$city,$region_id) = $regions_info[$val];

            $region['country'] = $country;
            $region['province'] = $province;
            $region['city'] = $city;
            $region['region'] = $region_id;

            if($key_id === false)
            {
                //add
                $flag = $this->add($region);
                $key_id = $flag;
            }
            else
            {
                //edit
                $flag = $this->edit($key_id,$region);

            }

            if(!$flag)
            {
                return false;
            }
            $ids_has[] = $key_id;
        }
        $ids_has = array_unique($ids_has);
        $ids_has = array_filter($ids_has);
        $ids_has[] = 0;
        //去除差异内容
        $sql = "delete from ".$this->table." where rule_id='{$rules_id}' and express_id='{$addon['express_id']}' and id not in( ". implode(',',$ids_has) ." ) ";

        $flag = $this->query($sql);
        if(!$flag)
        {
            $this->_error('清除规则地区时发生错误');
            return false;
        }
        return true;

    }


    /**
     * 把单个地址换成4个地址
     */
    private function region_address($regions)
    {
        if(empty($regions))
        {
            return array();
        }
        $model = m('region');
        $temp = $model->find("region_id in (". implode(',',$regions) .")");
        $data = array();
        foreach($temp as $val)
        {
            $data[$val['region_id']] = array($val['parent_id'],$val['region_id'],0,0);
        }

        return $data;
    }






} 